package com.web.segment.matching.dictionary;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.io.PrintStream;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;

/** 
 * @author Hades Guan 简单顺序词典接口 
 */  
public class SimpleDictionary implements Serializable, DictionaryImpl {  
    /** 
     * serialVersionUID 的注释 
     */  
    private static final long serialVersionUID = -6631832710612755332L;  
  
    /** 
     * 词典容器 
     */  
    private ArrayList<String> dic =  new ArrayList<String>();   
  
    /** 
     * 删除词典中的词word 
     *  
     * @param word 
     *            待删除的词汇 
     */  
    public void deleteWord(String word) {  
        if (word == null)  {
        	 return;  
        }
        int pos;  
        // 判断原词典中是否已有该词汇  
        if ((pos = Collections.binarySearch(dic, word)) < 0) {
        	return;
        } else {
        	 dic.remove(pos);  
        }
    }  
  
    /** 
     * 将词汇word插入到词典文件中 
     *  
     * @param word 
     *            待插入的词汇 
     */  
    public void insertWord(String word) {  
        if (word == null) {
            return;
        }
        // 判断原词典中是否已有该词汇  
        if (Collections.binarySearch(dic, word) < 0)  {
        	dic.add(word);  
        }
        // 插入后重新排序  
        Collections.sort(dic);  
    }  
  
    /** 
     * 载入以文本格式存储的词典 
     *  
     * @param fileName 
     *            词典的文件名 
     */  
    public void loadDictionary(String fileName) {  
        try {  
            // 初始化输入流  
            BufferedReader in = new BufferedReader(new FileReader(fileName));  
            String word = null;  
  
            // 读取词典  
            while ((word = in.readLine()) != null) {  
                dic.add(word);  
            }  
            // 词典排序  
            Collections.sort(dic);  
            // 关闭输入  
            in.close();  
        } catch (IOException e) {  
            // TODO 自动生成 catch 块  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * 判断输入的字符串是否在词典中 
     *  
     * @param word 
     *            待判断字符串 
     * @return 判断结果 
     */  
    public boolean match(String word) {  
        int pos = Collections.binarySearch(dic, word);  
        if (pos >= 0) {
        	return true;
        } else {
        	return false;
        }
    }  
  
    /** 
     * 输出已载入内存中所有词汇 
     *  
     * @param out 
     *            输出流 
     */  
    public void print(PrintStream out) {  
        for (int i = 0; i < this.dic.size(); i++) {  
            out.println(dic.get(i));  
        }  
        out.flush();  
    }  
  
}